package me.flyray.bsin.server.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.constants.ResponseCode;
import me.flyray.bsin.context.BsinServiceContext;
import me.flyray.bsin.domain.entity.AgentCard;
import me.flyray.bsin.domain.enums.AIAgentType;
import me.flyray.bsin.dubbo.invoke.BsinServiceInvoke;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.infrastructure.mapper.AgentCardMapper;
import me.flyray.bsin.security.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;


@Slf4j
@Component
public class AgentBiz {
    
    @Autowired
    private AgentCardMapper agentCardMapper;

    @Autowired private BsinServiceInvoke bsinServiceInvoke;

    /**
     * 构建AgentCard对象
     */
    public AgentCard buildAgentCardFromRequest(Map<String, Object> requestMap, LoginUser loginUser) {
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        
        // 设置业务角色信息
        agentCard.setBizRoleType(loginUser.getBizRoleType());
        agentCard.setBizRoleTypeNo(loginUser.getBizRoleTypeNo());
        
        // 设置租户ID
        Optional.ofNullable(agentCard.getTenantId())
                .or(() -> Optional.ofNullable(loginUser.getTenantId()))
                .ifPresentOrElse(
                        agentCard::setTenantId,
                        () -> { throw new BusinessException(ResponseCode.TENANT_ID_NOT_ISNULL); }
                );
        
        return agentCard;
    }
    
    /**
     * 更新已存在的智能体
     */
    public AgentCard updateExistingAgent(AgentCard agentCard) {
        agentCardMapper.updateById(agentCard);
        log.info("更新已存在的智能体，serialNo: {}", agentCard.getSerialNo());
        return agentCard;
    }
    
    /**
     * 处理智能体创建逻辑
     */
    public AgentCard processAgentCreation(AgentCard agentCard, String agentType, LoginUser loginUser) {
        if (AIAgentType.COMMON_APP_AGENT.getCode().equals(agentType)) {
            return createCommonAgent(agentCard);
        } else {
            return createUniqueAgent(agentCard, agentType, loginUser);
        }
    }
    
    /**
     * 创建通用智能体（可创建多个）
     */
    public AgentCard createCommonAgent(AgentCard agentCard) {
        agentCardMapper.insert(agentCard);
        log.info("创建通用agent智能体，serialNo: {}", agentCard.getSerialNo());
        return agentCard;
    }
    
    /**
     * 创建唯一智能体（每个业务角色只能创建一个）
     * 需要先开通did profile 才能创建数字分身
     */
    public AgentCard createUniqueAgent(AgentCard agentCard, String agentType, LoginUser loginUser) {

        Map<String, Object> requestMap = Map.of(
                "tenantId", loginUser.getTenantId(),
                "bizRoleType", loginUser.getBizRoleType(),
                "bizRoleTypeNo", loginUser.getBizRoleTypeNo()
        );

        // 验证业务角色是否已开通DID profile
        Object didProfile = bsinServiceInvoke.genericInvokeEngine("DidProfileServiceEngine", "getDetail", "dev", requestMap);
        if (didProfile == null) {
            log.warn("业务角色未开通DID profile，请先开通DID profile，bizRoleType: {}, bizRoleTypeNo: {}",
                    loginUser.getBizRoleType(), loginUser.getBizRoleTypeNo());
            throw new BusinessException(ResponseCode.DID_PROFILE_NOT_OPEN.getCode(), "业务角色未开通DID profile，请先开通DID profile");
        }

        // 查询是否已存在该类型的智能体
        AgentCard existingAgent = findExistingUniqueAgent(agentType, loginUser);
        
        if (existingAgent != null) {
            // 更新已存在的智能体
            agentCard.setSerialNo(existingAgent.getSerialNo());
            agentCardMapper.updateById(agentCard);
            log.info("更新已存在的{}智能体，serialNo: {}", getAgentTypeDesc(agentType), existingAgent.getSerialNo());
        } else {
            // 创建新的智能体
            agentCardMapper.insert(agentCard);
            log.info("创建新的{}智能体，serialNo: {}", getAgentTypeDesc(agentType), agentCard.getSerialNo());
        }
        
        return agentCard;
    }
    
    /**
     * 查找已存在的唯一智能体
     */
    public AgentCard findExistingUniqueAgent(String agentType, LoginUser loginUser) {
        LambdaQueryWrapper<AgentCard> wrapper = new LambdaQueryWrapper<AgentCard>()
                .eq(AgentCard::getTenantId, loginUser.getTenantId())
                .eq(AgentCard::getBizRoleType, loginUser.getBizRoleType())
                .eq(AgentCard::getBizRoleTypeNo, loginUser.getBizRoleTypeNo())
                .eq(AgentCard::getAgentType, agentType);
        
        return agentCardMapper.selectOne(wrapper);
    }
    
    /**
     * 根据智能体类型代码获取描述
     * @param agentType 智能体类型代码
     * @return 智能体类型描述
     */
    private String getAgentTypeDesc(String agentType) {
        AIAgentType type = AIAgentType.getInstanceById(agentType);
        return type != null ? type.getDesc() : "未知类型";
    }
}
